<?php

namespace App\Http\Controllers;

use App\Exceptions\BusinessException;
use App\Http\Response;
use App\Repository\AuthRepository;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    protected $repository;

    public function __construct()
    {
        $this->repository = new AuthRepository();
    }

    /**
     * 登录页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        return view('auth.login');
    }

    /**
     * @param Request $request
     * @return Response
     * @throws \App\Exceptions\ValidatorException
     */
    public function loginByPhone(Request $request)
    {
        return Response::success($this->repository->loginByFrom($request->input()));
    }

    public function password(Request $request)
    {
        $password = $request->input('password');
        $newPassword = $request->input('newPassword');
        return Response::success($this->repository->changePassword($password, $newPassword));
    }

    /**
     * 没有登录抛异常
     *
     * @throws BusinessException
     */
    public function login()
    {
        throw new BusinessException(BusinessException::UNAUTHORIZED, '没有授权', 401);
    }

    public function wxLogin(Request $request)
    {
        $code = $request->input('code');
        return Response::success($this->repository->getOpenID($code));
    }

    public function bind(Request $request)
    {
        $phone = $request->input('phone', 130);
        $openID = $request->input('openID');
        $user = $request->input('user', []);
        return Response::success($this->repository->bindOpenID($phone ?? '0', $openID, $user));
    }
}
